;
(function() {

	var BusCon = require("../../core/bus/_con");
	var UserCon = require("../../core/user/_con");
	var GoodsCon = require("../../core/goods/_con");
	var TagCon = require("../../core/bus.tag/_con");
	var ResponObj = require("../_include/responObj");
	var role = require("./role");
	var db = require("../../core/db/index");
	var config = require("../../core/_include/config");
	var data_cut = require("../../core/_include/data_cut");
	var db_table_name = config.dbname.visitorInfo;


	function getIpInfo(ip) {
		try {
			var data = JSON.parse(curl("http://ip.taobao.com/service/getIpInfo.php?ip=" + ip));
		} catch (e) {
			data = {
				data: {}
			};
		}
		return data;
	};
	module.exports = {
		prefix: "/visitorInfo",
		get: {
			"/": function() {
				var bus = role.getBus(this);
				var bus_id = bus._id;
				var num = this.request.query.num;
				var page = this.request.query.page;
				var visitor_info_list = db.find_list(db_table_name, {
					bus_id: bus_id
				});
				//排序
				visitor_info_list = db._sortBy(visitor_info_list, "last_visit_time", true);
				var result = data_cut.page(visitor_info_list, num, page);
				result.forEach(function(item) {
					if (item.user_id) {
						item.user = UserCon.get(item.user_id);
					}
				});
				this.body = ResponObj("json", result);
			},
			//官网的访问量统计
			"/www/num": function() {
				var query = this.request.query;
				var visitor_info_list = db.find_list(db_table_name, {
					bus_id: "www"
				});
				this.body = ResponObj("json", 35880 + visitor_info_list.length);
			},
			//统计
			"/statistical": function() {
				var bus = role.getBus(this);
				var bus_id = bus._id;
				var num = this.request.query.num;
				var page = this.request.query.page;
				var visitor_info_list = db.find_list(db_table_name, {
					bus_id: bus_id
				});
				//按最后访问时间排序
				visitor_info_list = db._sortBy(visitor_info_list, "last_visit_time", true);
				var visitor_info_map = {};
				var result = [];
				//合并相同IP，进行访问次数统计
				visitor_info_list.forEach(function(visitor_info) {
					var ip = visitor_info.user_ip.split(',')[0];
					if (ip.indexOf("127.0.0.1") === -1) {
						if (!visitor_info_map[ip]) {
							visitor_info_map[ip] = [];
							result.push(ip);
						}
						var visitor_info_set = visitor_info_map[ip];
						visitor_info_set.push(visitor_info);
					}
				});
				//截取数据
				result = data_cut.page(result, num, page);
				//数据整理
				result = result.map(function(ip) {
					var visitor_info_set = visitor_info_map[ip];
					return {
						ip: ip,
						set: visitor_info_set,
						ip_info_detail: visitor_info_set[0].ip_info_detail,
						last_visit_time: visitor_info_set[0].last_visit_time
					}
				});
				this.body = ResponObj("json", {
					total_number: visitor_info_list.length,
					statistical: result
				});
			},
			"/ip/:ip": function() {
				var ip = this.params.ip;
				if (!ip) {
					throwCusError("参数错误")
				}
				this.body = ResponObj("json", getIpInfo(ip));
			}
		},
		post: {
			"/": function() {
				var bus_id = this.request.body.bus_id;
				var req = this.req;
				try {
					var user = role.getUser(this);
					var user_id = user._id;
				} catch (e) {}

				this.proxy = true;
				var ipAddress = this.request.headers["user_ip"];

				console.log("user visit:", ipAddress, this.request.headers["user-agent"], this.response.get("access-control-allow-origin"));

				if (bus_id) {
					var _now = Date.now();
					if (bus_id === "www") { //官网访问的访问频率而外算
						var accessIntervals = config.wwwAccessIntervals;
					} else {
						accessIntervals = config.accessIntervals;
					}
					var visitor_info_list = db.find_all(db_table_name);
					var _finder_obj = {
						bus_id: bus_id,
						user_ip: ipAddress
					};
					//因为是根据begin_visit_time来插入，所以不需要遍历全部，只需要找到寻找时间段内的数据
					//begin_visit_time --{accessIntervals}-- last_visit_time
					//last_visit_time和begin_visit_time相差不超过accessIntervals
					//超过的话，就拆开来，作为新的访问量加入
					for (var i = visitor_info_list.length - 1; i >= 0; i -= 1) {
						var _current_visitor_info = visitor_info_list[i];
						//先判断时间，比较好判断
						if (_current_visitor_info.begin_visit_time + accessIntervals >= _now) {
							if (_current_visitor_info.bus_id === bus_id && _finder_obj.user_ip === ipAddress && (_finder_obj.user_id || "") === (user_id || "")) {
								var visitor_info = _current_visitor_info;
								break
							}
						} else {
							//因为是根据begin_visit_time插入，超过这个时间段的话，后面就不用遍历了
							break;
						}
					}

					if (visitor_info) {
						//刷新上一次的访问时间
						visitor_info.last_visit_time = _now;

						db.update(db_table_name, visitor_info._id, visitor_info);
					} else {
						//IP地理信息
						var ip_info = getIpInfo(ipAddress).data;
						visitor_info = {
							_id: config.dbIdPrefix.visitorInfo + Math.random().toString(16).substr(2) + (+new Date).toString(16),
							bus_id: bus_id,
							user_id: user_id,
							user_ip: ipAddress,
							ip_info: ip_info,
							ip_info_detail: ip_info.city,
							last_visit_time: +new Date,
							begin_visit_time: +new Date
						}
						db.insert(db_table_name, visitor_info);
					}
					this.body = ResponObj("json", visitor_info);
				} else {
					throwCusError("参数错误")
				}
			}
		}
	};

}());